<?php

namespace App\Http\Controllers\College\Web;

use App\Http\Controllers\BaseController;
use App\Service\BaseService;
use App\Service\College\CategoryService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class CategoryController extends BaseController
{


    /**
     * 课程分类列表
     * @param Request $request
     * @return JsonResponse
     */
    public function list(Request $request)
    {
        $data = CategoryService::getCategoryList($request);
        return $this->success($data);
    }

    /**
     * 添加分类
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws \Exception
     */
    public function add(Request $request): JsonResponse
    {
        $this->validate($request, [
            'name' => 'required|string|max:20',
            'sort' => 'required|integer|max:255',
        ]);
        CategoryService::addCategory($request);
        return $this->success();
    }


    /**
     *
     * 修改分类名称
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ValidationException
     * @throws \Exception
     */
    public function update(Request $request): JsonResponse
    {
        $this->validate($request, [
            'name' => 'required|string|max:20',
            'sort' => 'required|integer|max:255',
        ]);
        if (empty($request->id)) {
            return BaseService::throwErr("id不能为空");
        }
        CategoryService::updateCategory($request);
        return $this->success();
    }

    /**
     * get info
     * @param Request $request
     * @return JsonResponse
     */
    public function info(Request $request)
    {
        if (empty($request->id)) {
            return BaseService::throwErr("id不能为空");
        }
        $data = CategoryService::getCategoryInfo($request);
        if (!empty($data)) {
            $data = $data->toArray();
        }
        return $this->success($data);
    }

    /**
     * 删除分类
     * @param Request $request
     * @return JsonResponse
     * @throws \Exception
     */
    public function delete(Request $request)
    {
        if (empty($request->id)) {
            return BaseService::throwErr("id不能为空");
        }
        $res = CategoryService::deleteCategory($request);
        if ($res) {
            return $this->fail(403, '该分类下有' . $res . '个课程，无法删除');
        }
        return $this->success();
    }
}
